package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.AddFamilyDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zsh
 * @version 1.0
 * @since 2025-08-29 11:17
 */
@Service
public class IFamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements IFamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(AddFamilyDto addFamilyDto) {

        String idCard = addFamilyDto.getIdCard();
        String name = addFamilyDto.getName();
        String remark = addFamilyDto.getRemark();
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, idCard);
        queryWrapper.eq(Elder::getName, name);
        Elder selectedElder = elderMapper.selectOne(queryWrapper);
        if(ObjUtil.isNull(selectedElder)){
            throw new RuntimeException("该老人不存在");
        }
        //获取用户ID
        Long userId = MemberThreadLocal.getMemberId();
        //判断状态为1，2, 4
        if(!selectedElder.getStatus().equals(1) && !selectedElder.getStatus().equals(2) && !selectedElder.getStatus().equals(4)){
            throw new RuntimeException("该老人状态为：" + selectedElder.getStatus() + "，不能进行退住操作");
        }
        //插入FamilyMemberElder
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(selectedElder.getId());
        familyMemberElder.setMemberId(userId);
        familyMemberElder.setCreateBy(userId.toString());
        familyMemberElder.setRemark(remark);

        //保存到数据库中
        familyMemberElderMapper.add(familyMemberElder);
        return 1;
    }

    /**
     * 查询家人列表
     * @param
     * @return
     */



}
